import {StoreRoot, mapSet} from "@/stores/StoreRoot";
import Common from "@/lib/Common";

export class StoreBase {
    _name = undefined
    _storeKey = undefined
    _parent = undefined
    _children = new Map()

    constructor({name, parent}) {
        if (!name) {
            throw new Error('property name is required')
        }
        this._name = name
        this._storeKey = Common.toSymbol(name)
        this._parent = parent
    }

    get storeKey() {
        return this._storeKey
    }

    get parent() {
        return this._parent
    }

    get children() {
        return this._children
    }

    get name() {
        return this._name
    }

    get childrenValues() {
        return Array.from(this._children.values())
    }

    /**
     * 设置一个状态
     * @param store
     */
    set(store, replace = false) {
        mapSet(this.children, store, this, replace)
    }

    get(storeKey) {
        const symboxStoreKey = Common.toSymbol(storeKey)
        return this._children.get(symboxStoreKey)
    }

    delete(storeKey) {
        const symboxStoreKey = Common.toSymbol(storeKey)
        StoreRoot.delete(symboxStoreKey)
        return this._children.delete(symboxStoreKey)
    }

    has(storeKey) {
        const symboxStoreKey = Common.toSymbol(storeKey)
        return this._children.has(symboxStoreKey)
    }

    clear() {
        this._children.forEach((value, key) => {
            StoreRoot.delete(key)
        })
        this._children.clear()
    }


}

